package com.sise.dubbo.config.loadBalanceSpi;

import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.cluster.LoadBalance;

import java.time.LocalTime;
import java.util.List;
import java.util.Random;

/**
 * 假设说现在有个需求，要求9-18点请求A机器，18-23点请求B机器，其余时间任意请求，
 * 那么这个负载均衡该如何实现
 *
 * @author idea
 * @data 2019/5/18
 */
public class MyLoadBalance implements LoadBalance {

    private final String A_MACHINE_HOST_PORT = "192.168.43.191:20880";

    private final String B_MACHINE_HOST_PORT = "192.168.43.191:20880";

    @Override
    public <T> Invoker<T> select(List<Invoker<T>> list, URL url, Invocation invocation) throws RpcException {
        System.out.println("执行自定义的负载均衡算法");
        //模拟场景，只有两台服务器作为支撑
        System.out.println(url);
        int currentHour = LocalTime.now().getHour();
        if (currentHour >= 9 && currentHour <= 18) {
            System.out.println("请求A机器");
            findInvokerInList(list, A_MACHINE_HOST_PORT);
        } else if (currentHour >= 18 && currentHour <= 23) {
            System.out.println("请求B机器");
            findInvokerInList(list, B_MACHINE_HOST_PORT);
        }
        int randIndex = new Random().nextInt(list.size());
        return list.get(randIndex);
    }


    /**
     * 从服务列表里面进行dubbo服务地址匹配
     *
     * @param list
     * @param matchKey
     * @param <T>
     * @return
     */
    private <T> Invoker findInvokerInList(List<Invoker<T>> list, String matchKey) {
        for (Invoker tInvoker : list) {
            String addr = tInvoker.getUrl().getHost() + tInvoker.getUrl().getPort();
            if (matchKey.equals(addr)) {
                return tInvoker;
            }
        }
        return null;
    }
}
